<template>
  <div class="server-detail p-4">
    <el-card class="box-card">
      <template #header>
        <div class="card-header flex items-center justify-between">
          <h2 class="text-xl font-bold">服务器详情</h2>
          <div class="flex gap-2">
            <el-button type="primary" @click="goToEdit(serverId)">编辑</el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <div v-loading="loading">
        <el-descriptions v-if="serverData" :column="2" border>
          <!-- 基础信息 -->
          <template #title>
            <div class="text-lg font-medium">基础信息</div>
          </template>
          <el-descriptions-item label="IP地址">{{ serverData.ip }}</el-descriptions-item>
          <el-descriptions-item label="主机名">{{ serverData.hostname }}</el-descriptions-item>
          <el-descriptions-item label="产品线">{{ serverData.product_line || '-' }}</el-descriptions-item>
          <el-descriptions-item label="服务器类型">
            <el-tag :type="getServerTypeTag(serverData.server_type)">
              {{ getServerTypeName(serverData.server_type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="服务器状态">
            <el-tag :type="getStatusTag(serverData.server_status)">
              {{ getStatusName(serverData.server_status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="使用状态">
            <el-tag :type="getUsageStatusTag(serverData.usage_status)">
              {{ getUsageStatusName(serverData.usage_status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="环境">
            <el-tag v-if="serverData.environment" :type="getEnvironmentTag(serverData.environment)">
              {{ getEnvironmentName(serverData.environment) }}
            </el-tag>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="序列号">{{ serverData.sn || '-' }}</el-descriptions-item>
          <el-descriptions-item label="机柜位置">{{ serverData.rack_location || '-' }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ serverData.notes || '-' }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 物理配置信息 -->
        <el-descriptions v-if="serverData && hasPhysicalInfo" class="mt-4" :column="2" border>
          <template #title>
            <div class="text-lg font-medium">物理配置信息</div>
          </template>
          <el-descriptions-item label="CPU型号">{{ serverData.cpu_model || '-' }}</el-descriptions-item>
          <el-descriptions-item label="CPU核心数">{{ serverData.cpu_cores ? `${serverData.cpu_cores}核` : '-' }}</el-descriptions-item>
          <el-descriptions-item label="CPU线程数">{{ serverData.cpu_threads ? `${serverData.cpu_threads}线程` : '-' }}</el-descriptions-item>
          <el-descriptions-item label="内存大小">{{ serverData.memory_size ? `${serverData.memory_size}GB` : '-' }}</el-descriptions-item>
          <el-descriptions-item label="磁盘大小">{{ serverData.disk_size ? `${serverData.disk_size}GB` : '-' }}</el-descriptions-item>
          <el-descriptions-item label="系统版本">{{ serverData.system_version || '-' }}</el-descriptions-item>
          <el-descriptions-item label="内核版本">{{ serverData.kernel_version || '-' }}</el-descriptions-item>
          <el-descriptions-item label="运行时长">{{ serverData.uptime ? `${formatUptime(serverData.uptime)}` : '-' }}</el-descriptions-item>
          <el-descriptions-item label="购买日期">{{ serverData.purchase_date ? formatDate(serverData.purchase_date) : '-' }}</el-descriptions-item>
          <el-descriptions-item label="磁盘详情" :span="2">
            <pre v-if="serverData.disk_info" class="whitespace-pre-wrap text-sm">{{ formatDiskInfo(serverData.disk_info) }}</pre>
            <span v-else>-</span>
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 时间信息 -->
        <el-descriptions v-if="serverData" class="mt-4" :column="2" border>
          <template #title>
            <div class="text-lg font-medium">时间信息</div>
          </template>
          <el-descriptions-item label="创建时间">{{ serverData.created_at }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ serverData.updated_at }}</el-descriptions-item>
        </el-descriptions>
        
        <el-empty v-else description="未找到服务器信息" />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="ServerDetail">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getServer } from '@/request/server-api'
import { ServerType, ServerStatus, ServerUsageStatus, ServerEnvironment } from '@/model/server-model'
import type { Server } from '@/model/server-model'
import dayjs from 'dayjs'

// 路由对象
const router = useRouter()
const route = useRoute()

// 服务器ID
const serverId = ref(Number(route.params.id) || 0)

// 服务器数据
const serverData = ref<Server | null>(null)

// 加载状态
const loading = ref(false)

/**
 * 获取服务器详情
 */
const getServerDetail = async () => {
  if (!serverId.value) {
    ElMessage.error('服务器ID无效')
    goBack()
    return
  }

  loading.value = true
  try {
    const response = await getServer(serverId.value)
    if (response.code === 0) {
      serverData.value = response.data
    } else {
      ElMessage.error(response.errorMsg || '获取服务器详情失败')
      goBack()
    }
  } catch (error) {
    console.error('获取服务器详情失败:', error)
    ElMessage.error('获取服务器详情失败')
    goBack()
  } finally {
    loading.value = false
  }
}

/**
 * 获取服务器类型标签类型
 */
const getServerTypeTag = (type: ServerType): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  switch (type) {
    case ServerType.WEB:
      return 'primary'
    case ServerType.DATABASE:
      return 'success'
    case ServerType.APPLICATION:
      return 'warning'
    case ServerType.FILE:
      return 'info'
    case ServerType.CACHE:
      return 'success'
    case ServerType.PROXY:
      return 'primary'
    default:
      return 'info'
  }
}

/**
 * 获取服务器类型名称
 */
const getServerTypeName = (type: ServerType): string => {
  switch (type) {
    case ServerType.WEB:
      return 'Web服务器'
    case ServerType.DATABASE:
      return '数据库服务器'
    case ServerType.APPLICATION:
      return '应用服务器'
    case ServerType.FILE:
      return '文件服务器'
    case ServerType.CACHE:
      return '缓存服务器'
    case ServerType.PROXY:
      return '代理服务器'
    case ServerType.OTHER:
      return '其他'
    default:
      return type
  }
}

/**
 * 获取状态标签类型
 */
const getStatusTag = (status: ServerStatus): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  switch (status) {
    case ServerStatus.ONLINE:
      return 'success'
    case ServerStatus.OFFLINE:
      return 'danger'
    case ServerStatus.MAINTENANCE:
      return 'warning'
    case ServerStatus.DECOMMISSIONED:
      return 'info'
    default:
      return 'info'
  }
}

/**
 * 获取状态名称
 */
const getStatusName = (status: ServerStatus): string => {
  switch (status) {
    case ServerStatus.ONLINE:
      return '在线'
    case ServerStatus.OFFLINE:
      return '离线'
    case ServerStatus.MAINTENANCE:
      return '维护中'
    case ServerStatus.DECOMMISSIONED:
      return '已退役'
    default:
      return status
  }
}

/**
 * 获取使用状态标签类型
 */
const getUsageStatusTag = (status: ServerUsageStatus): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  switch (status) {
    case ServerUsageStatus.IN_USE:
      return 'primary'
    case ServerUsageStatus.AVAILABLE:
      return 'success'
    case ServerUsageStatus.RESERVED:
      return 'warning'
    case ServerUsageStatus.RETIRED:
      return 'info'
    default:
      return 'info'
  }
}

/**
 * 获取使用状态名称
 */
const getUsageStatusName = (status: ServerUsageStatus): string => {
  switch (status) {
    case ServerUsageStatus.IN_USE:
      return '使用中'
    case ServerUsageStatus.AVAILABLE:
      return '可用'
    case ServerUsageStatus.RESERVED:
      return '已预留'
    case ServerUsageStatus.RETIRED:
      return '已报废'
    default:
      return status
  }
}

/**
 * 获取环境标签类型
 */
const getEnvironmentTag = (environment?: ServerEnvironment): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  if (!environment) return 'info'
  switch (environment) {
    case ServerEnvironment.TESTING:
      return 'info'
    case ServerEnvironment.DEVELOPMENT:
      return 'warning'
    case ServerEnvironment.PRODUCTION:
      return 'success'
    default:
      return 'info'
  }
}

/**
 * 获取环境名称
 */
const getEnvironmentName = (environment?: ServerEnvironment): string => {
  if (!environment) return '-'
  switch (environment) {
    case ServerEnvironment.TESTING:
      return '测试环境'
    case ServerEnvironment.DEVELOPMENT:
      return '开发环境'
    case ServerEnvironment.PRODUCTION:
      return '线上环境'
    default:
      return environment
  }
}

/**
 * 返回列表页
 */
const goBack = () => {
  router.push('/server/list')
}

/**
 * 跳转到编辑页面
 */
const goToEdit = (id: number) => {
  router.push(`/server/edit/${id}`)
}

/**
 * 计算属性：判断是否有物理信息
 */
const hasPhysicalInfo = computed(() => {
  if (!serverData.value) return false
  return !!(serverData.value.cpu_model || 
    serverData.value.cpu_cores || 
    serverData.value.cpu_threads || 
    serverData.value.memory_size || 
    serverData.value.disk_size || 
    serverData.value.disk_info || 
    serverData.value.system_version || 
    serverData.value.kernel_version || 
    serverData.value.uptime || 
    serverData.value.purchase_date)
})

/**
 * 格式化运行时长
 * @param hours 小时数
 * @returns 格式化后的运行时长
 */
const formatUptime = (hours: number): string => {
  const days = Math.floor(hours / 24)
  const remainingHours = Math.floor(hours % 24)
  let result = ''
  
  if (days > 0) {
    result += `${days}天`
  }
  
  if (remainingHours > 0 || result === '') {
    result += `${remainingHours}小时`
  }
  
  return result
}

/**
 * 格式化日期
 * @param dateStr 日期字符串
 * @returns 格式化后的日期
 */
const formatDate = (dateStr: string): string => {
  return dayjs(dateStr).format('YYYY-MM-DD')
}

/**
 * 格式化磁盘信息
 * @param diskInfoStr 磁盘信息JSON字符串
 * @returns 格式化后的磁盘信息
 */
const formatDiskInfo = (diskInfoStr: string): string => {
  try {
    const diskInfo = JSON.parse(diskInfoStr)
    let formattedInfo = ''
    
    for (const [disk, info] of Object.entries(diskInfo)) {
      const diskData = info as { size_gb: number; mount: string }
      formattedInfo += `${disk}: ${diskData.size_gb}GB, 挂载点: ${diskData.mount}\n`
    }
    
    return formattedInfo || '无详细信息'
  } catch (error) {
    console.error('解析磁盘信息失败:', error)
    return diskInfoStr // 如果解析失败，直接返回原始字符串
  }
}

onMounted(() => {
  getServerDetail()
})
</script>
